package com.hzwq.demo2.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzwq.demo2.user.entity.User;
import com.hzwq.demo2.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    IUserService userService;

    @RequestMapping("/NoPer")
    public ModelAndView toNoPer() {
        ModelAndView mav = new ModelAndView("nopermission/NoPer");
        return mav;
    }

    @RequestMapping("/login")
    public ModelAndView toLogin() {
        ModelAndView mav = new ModelAndView("index/login");
        return mav;
    }

    @RequestMapping("/tologin")
    public void login(HttpSession session, HttpServletRequest request, HttpServletResponse response,String username,String password) throws ServletException, IOException {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        System.out.println(username);
        System.out.println(password);
        wrapper.eq("user_name",username);
        wrapper.eq("pass_word",password);
        User res = userService.getOne(wrapper);
        if(res != null){
            res = userService.getById(res.getId());
            session.setAttribute("user",res);
            response.sendRedirect("user/index");
        } else {
            response.sendRedirect("login");
        }


    }

    @RequestMapping("/logout")
    public ModelAndView logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView mav = new ModelAndView("/index/login");
        session.removeAttribute("user");
        return mav;
    }

}
